﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CrmApplication.Models;

namespace CrmApplication.Controllers
{
    public class CityController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// get all cities list  by county id
        /// </summary>
        /// <returns></returns>
        public ActionResult GetCity()
        {
            string searchCity = Request.Params["city"];
            decimal countyId = 0;
            Decimal.TryParse(Request.Params["county_id"], out countyId);

            CityContainer container = CityModels.GetCityArray(searchCity, countyId);

            return Json(container, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// get all cities list
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllCity()
        {
            string searchCity = Request.Params["city"];
            
            CityContainer container = CityModels.GetAllCityArray(searchCity);

            return Json(container, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// add new city
        /// </summary>
        /// <returns></returns>
        public ActionResult AddCity()
        {
            decimal countyId = 0;
            Decimal.TryParse(Request.Params["county"], out countyId);

            CityModels city = new CityModels();

            city.Name = Request.Params["city"];
            city.IdCounty = countyId;

            CityModels checkCity = new CityModels();
            checkCity = CityModels.CheckCity(city);

            string messageBack = null;

            try
            {
                if (city.Name != "")
                {
                    if (checkCity == null)
                    {
                        CityModels.AddCity(city);
                    }
                    else
                    {
                        messageBack = "Orasul  exista deja!";
                    }
                }
				return Json(new { success = true, description = messageBack });
            }            
            catch (Exception ex)
            {

				if (ex.Message.Contains("unique key constraint"))
				{
					messageBack = "Exista deja o inregistrare cu acelasi nume";
				}
				return Json(new { success = true, description = messageBack });
            }
        }
    }
}
